YUI.add('javascript-section', function (Y) {
    /* Any frequently used shortcuts, strings and constants */
    var Lang = Y.Lang;

    /* JavascriptSection class constructor */
    function JavascriptSection(config) {
        JavascriptSection.superclass.constructor.apply(this, arguments);
    }

    /* 
     * Required NAME static field, to identify the class and 
     * used as an event prefix, to generate class names etc. (set to the 
     * class name in camel case). 
     */
    JavascriptSection.NAME = "JavascriptSection";
    
    JavascriptSection.JSONP_URL = "http://www.m3958.com";
    
//    if(window.location.href.indexOf('8888') != -1){
//    	JavascriptSection.JSONP_URL = "http://127.0.0.1:8888";
//    }
    
    var myDataSource = new Y.DataSource.Get({
        source: JavascriptSection.JSONP_URL + "/smartcfud?_jsonp=true&_anonymous=true&audit=true&_isMaster=false&_modelName=com.m3958.firstgwt.server.model.Article&_operationType=fetch&_relationModelName=com.m3958.firstgwt.server.model.Section&_relationPropertyName=articles&_sortBy=-publishedAt&_subOperationType=MANY_TO_MANY&_textMatchStyle=substring&_jsonv=v"
    });
    
//    "status":0,"startRow":0,"endRow":5,"totalRows"
    myDataSource.plug(Y.Plugin.DataSourceJSONSchema, {
        schema: {
        	metaFields : {status:'response.status',startRow:'response.startRow',endRow:'response.endRow',totalRows:'response.totalRows'},
            resultListLocator: "response.data",
            resultFields: ['title','id','content','excerpt','titleImg','contentImgs','attachments',"keyValues","publishedAt","url"]
        }
    });
    
    myDataSource.plug(Y.Plugin.DataSourceCache, { max: 100 });

    /*
     * The attribute configuration for the component. This defines the core user facing state of the component
     */
    JavascriptSection.ATTRS = {
    	section : {
    		value : null
    	},
    	siteId : {
    		value : null
    	},
        attrA : {
            value: "A"                     // The default value for attrA, used if the user does not set a value during construction.

            /*
            , valueFn: "_defAttrAVal"      // Can be used as a substitute for "value", when you need access to "this" to set the default value.
             
            , setter: "_setAttrA"          // Used to normalize attrA's value while during set. Refers to a prototype method, to make customization easier
            , getter: "_getAttrA"          // Used to normalize attrA's value while during get. Refers to a prototype method, to make customization easier
            , validator: "_validateAttrA"  // Used to validate attrA's value before updating it. Refers to a prototype method, to make customization easier

            , readOnly: true               // Cannot be set by the end user. Can be set by the component developer at any time, using _set
            , writeOnce: true              // Can only be set once by the end user (usually during construction). Can be set by the component developer at any time, using _set
            
            , lazyAdd: false               // Add (configure) the attribute during initialization. 
            
                                           // You only need to set lazyAdd to false if your attribute is
                                           // setting some other state in your setter which needs to be set during initialization 
                                           // (not generally recommended - the setter should be used for normalization. 
                                           // You should use listeners to update alternate state). 

            , broadcast: 1                 // Whether the attribute change event should be broadcast or not.
            */
        }

        // ... attrB, attrC, attrD ... attribute configurations. 

        // Can also include attributes for the super class if you want to override or add configuration parameters
    };

    /* JavascriptSection extends the Base class */
    Y.extend(JavascriptSection, Y.Base, {
        initializer: function() {
            /*
             * initializer is part of the lifecycle introduced by 
             * the Base class. It is invoked during construction,
             * and can be used to setup instance specific state or publish events which
             * require special configuration (if they don't need custom configuration, 
             * events are published lazily only if there are subscribers).
             *
             * It does not need to invoke the superclass initializer. 
             * init() will call initializer() for all classes in the hierarchy.
             */
//        	this.cached = {};
//        	this.articleFetched = false;
        	this.meta = null;
             this.publish("articleFetched", {
                defaultFn: this._onarticleFetched,
                bubbles:false
             });
        },

        destructor : function() {
            /*
             * destructor is part of the lifecycle introduced by 
             * the Base class. It is invoked when destroy() is called,
             * and can be used to cleanup instance specific state.
             *
             * It does not need to invoke the superclass destructor. 
             * destroy() will call initializer() for all classes in the hierarchy.
             */
        },
        
//		_handleArticleJSONP : function(data,start,size) {
//			if(data.response.status == 0){
//				this.articleFetched = true;
//				var ars = Y.Array.map(data.response.data,function(a){
//					return new Y.M3958.JavascriptArticle({article:a});
//				});
//				this.cached[start + ',' + size] = ars;
//				this.articles = ars
//	    	    this.fire('articleFetched',{success:true,articles:ars});
//			}else{
//				this.fire('articleFetched',{success:false,msg:data.response.data[0].message});
//			}
//		},
		
		_datasourceSuccess : function(extra,e){
			var data = e.response.results;
			this.meta = e.response.meta;
			var ars = Y.Array.map(data,function(a){
				return new Y.M3958.JavascriptArticle({article:a});
			});
			this.lastFetched = ars;
			this.fire('articleFetched',{success:true,articles:ars,extra:extra});
		},
		
		_datasourceFailure : function(e){
			Y.log(e);
		},
		
		gett : function(fieldName){
			return this.get('section')[fieldName];
		},
        
		findArticle : function(aid){
			if(Y.Lang.isString(aid)){
				aid = parseInt(aid);
			}
			if(this.lastFetched){
				return Y.Array.find(this.lastFetched,function(item){
					return item.gett('id') == aid;
				});
			}
		},
		
//		section.fetchArticles(0,5,{usage:['slide']});
		fetchArticles : function(start,size,extra){
			var outThis = this;
		    myDataSource.sendRequest({
		        request: "&siteId=" + this.gett('siteId') + "&_endRow=" + (start + size) + "&_relationModelId=" + this.gett('id') + "&_startRow=" + start,
		        callback: {
		            success: Y.bind(outThis._datasourceSuccess,outThis,extra),
		            failure: outThis._datasourceFailure
		        }
		    });
		},

        doSomethingPublic : function() {
            // Public method
        },

        _doSomethingPrivate : function() {
            // Private/Protected method
        },

        _onarticleFetched : function(e) {
            // The default behavior for the "siteReady" event.
        }
    });
  
/*		
_endRow=50&_isMaster=false&_modelName=com.m3958.firstgwt.server.model.Article&_operationType=fetch&_relationModelId=18245&_relationModelName=com.m3958.firstgwt.server.model.Section&_relationPropertyName=articles&_sortBy=-publishedAt&	_startRow=0&_subOperationType=MANY_TO_MANY&_textMatchStyle=substring
*/		
    Y.namespace("M3958").JavascriptSection = JavascriptSection;

},'0.0.1',{requires:['base',"datasource-get", "datasource-jsonschema",'node',"datasource-cache",'javascript-article']});